package com.wing.user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.user.dao.RoleDao;
import com.wing.user.dao.SystemDingTalkInfoDao;
import com.wing.user.model.entity.*;
import com.wing.user.model.response.NodeDataVO;
import com.wing.user.utils.DingDingUtils;
import com.wing.web.excel.RoleExcelIn;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleDao, Role> implements RoleService {

    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private DepartmentService departmentService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        this.removeById(id);
        roleMenuService.remove(new QueryWrapper<RoleMenu>().eq("menu_id", id));
    }

    @Override
    public Page<Role> pageList4app(Page page, Map<String, Object> params) {
        List<Role> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<Role> list4app(Map<String, Object> params) {
        List<Role> list = baseMapper.list4app(null, params);
        return list;
    }

    @Override
    public List<Role> getRoleData(List<Long> ids) {
        return baseMapper.getRoleData(ids);
    }

    @Override
    public void importExcel(List<RoleExcelIn> list) {
        try {
            addExcel(list);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<RoleExcelIn> exportList(Map paramsMap) {
        return baseMapper.exportList(paramsMap);
    }

    @Transactional(readOnly = false)
    public void addExcel(List<RoleExcelIn> list) {
        //部门岗位列表
        List<Role> roleList = this.baseMapper.selectList(null);
        int i = 1;
        for (RoleExcelIn item : list) {
            i++;
            if (StringUtils.isBlank(item.getCompanyInfoName())) {
                throw new BusinessException(300, "第" + i + "行企业未输入数据");
            }
            if (StringUtils.isBlank(item.getName())) {
                throw new BusinessException(300, "第" + i + "行名称未输入数据");
            }
            if (StringUtils.isBlank(item.getCode())) {
                throw new BusinessException(300, "第" + i + "行编码未输入数据");
            }
            if (StringUtils.isBlank(item.getIsProduceVal())) {
                throw new BusinessException(300, "第" + i + "行层级性质未输入数据");
            }
            Role role = new Role();
            // 获取企业
            CompanyInfo companyInfo = companyInfoService.getOne(new QueryWrapper<CompanyInfo>().eq("name", item.getCompanyInfoName()));
            if (companyInfo == null) {
                throw new BusinessException(300, "该企业数据不存在");
            }

            //部门信息
            Role department = roleList.stream().filter(t -> StringUtils.isNotBlank(item.getDepartmentName()) && t.getName().equals(item.getDepartmentName())).findFirst().orElse(null);
            if (department != null) {
                role.setParentId(department.getId());
            }

            Boolean isProduceVal = false;
            if (StringUtils.isNotBlank(item.getIsProduceVal()) && item.getIsProduceVal().indexOf("部门") != -1) {
                isProduceVal = true;
            }
            role.setCompanyInfoId(companyInfo.getId());
            role.setName(item.getName());
            role.setCode(item.getCode());
            role.setIsProduce(isProduceVal);
            role.setIsDeleted(true);
            if (StringUtils.isNotBlank(item.getSocialSecurityBase())) {
                role.setSocialSecurityBase(Integer.parseInt(item.getSocialSecurityBase()));
            }
            if (StringUtils.isNotBlank(item.getProvidentFundBase())) {
                role.setProvidentFundBase(Integer.parseInt(item.getProvidentFundBase()));
            }
            if (baseMapper.insert(role) <= 0) {
                throw new BusinessException(500, "导入失败");
            }
        }
    }

    public JsonResult getTreeData(Long roleId) {
        List<Long> roleIdList = new ArrayList<>();
        if (roleId != null) {
            List<Role> roleList = this.baseMapper.getRoleHierarchy(roleId);
            roleIdList = roleList.stream().map(t -> t.getId()).collect(Collectors.toList());
        }
        QueryWrapper<Role> queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_produce", 1);
        if (roleId != null) {
            queryWrapper.notIn("id", roleIdList);
        }
        List<Role> list = this.baseMapper.selectList(queryWrapper);
        Map<Long, List<NodeDataVO>> map = new HashMap<>();
        for (Role role : list) {
            if (map.containsKey(role.getParentId())) {
                NodeDataVO nodeDataVO = new NodeDataVO();
                nodeDataVO.setValue(role.getId().toString());
                nodeDataVO.setName(role.getName());
                map.get(role.getParentId()).add(nodeDataVO);
            } else {
                List<NodeDataVO> tmpList = new ArrayList<>();
                NodeDataVO nodeDataVO = new NodeDataVO();
                nodeDataVO.setValue(role.getId().toString());
                nodeDataVO.setName(role.getName());
                tmpList.add(nodeDataVO);
                map.put(role.getParentId(), tmpList);
            }
        }
        List<NodeDataVO> rootList = map.get(-1L);
        if (rootList == null) {
            return JsonResult.success();
        }
        constructTree(rootList, map);
        return JsonResult.success(rootList);
    }

    @Override
    public List<Role> getRoleHierarchy(Long roleId) {
        return this.baseMapper.getRoleHierarchy(roleId);
    }

    private void constructTree(List<NodeDataVO> parentList, Map<Long, List<NodeDataVO>> dataMap) {
        for (NodeDataVO node : parentList) {
            Long nodeId = Long.valueOf(node.getValue());
            List<NodeDataVO> childList = dataMap.get(nodeId);
            if (childList != null) {
                node.setChildren(childList);
                constructTree(childList, dataMap);
            }
        }
    }


    @Autowired
    SystemDingTalkInfoDao systemDingTalkInfoDao;

    @Override
    public  void syncDingDeptToSysRole() throws Exception {
        SystemDingTalkInfo systemDingTalkInfo = systemDingTalkInfoDao.selDingTalkInfo();
  /*       DingDingVO dingDingVO = baseMapper.selDingTalkInfo();
         if(dingDingVO!=null){*/
        if(systemDingTalkInfo!=null){
            String accessToken = DingDingUtils.getAccessTokenByKeySecret(systemDingTalkInfo.getClientId(), systemDingTalkInfo.getClientSecret());
            //获取顶层部门信息 公司那一层
            String deptDetail = DingDingUtils.getDeptDetail(accessToken, 1L);
            com.alibaba.fastjson.JSONObject topDeptDetail = com.alibaba.fastjson.JSONObject.parseObject(deptDetail);
            ObjectMapper objectMapper = new ObjectMapper();
            Long topParentId=null;
            try {
                // 解析输入的JSON字符串
                JsonNode rootNode = objectMapper.readTree(String.valueOf(topDeptDetail));

                // 获取result节点
                JsonNode resultNode = rootNode.path("result");
                int deptId = resultNode.path("dept_id").asInt();
                String name = resultNode.path("name").asText();

                Role role = new Role();
                role.setName(name);
                role.setSortNumber(1);
                role.setIsProduce(true); // 如果没有子部门，则设置为false，否则为true
                role.setIsDeleted(true);
                role.setDingDepartmentId(Long.valueOf(deptId));
                //TODO 取根部门下面的夫定的编码
                role.setDingParentId(1L);
                role.setCode(generateSixDigitNumber(name));
                Role role2 = baseMapper.getRoleDepartData(null, Long.valueOf(deptId));
                if(role2 != null){
                    role.setId(role2.getId());
                    baseMapper.updateById(role);
                } else {
                    baseMapper.insert(role);
                }
                topParentId=role.getId();
            } catch (Exception e) {
                e.printStackTrace();
                log.info("同步根部门数据出现异常: " + e);
            }
             // 从根部门开始同步（假设根部门ID为1）
            syncDingDeptToSysRole(accessToken, "1",topParentId);
        }
    }



    /**
     * 递归同步钉钉部门到系统角色
     * @param accessToken 访问令牌
     * @param parentId 父部门ID
     * @throws Exception 如果发生错误
     */
    private void syncDingDeptToSysRole(String accessToken, String parentId,Long topParentId) throws Exception {
        // 获取指定parentId下的部门列表
        String deptInfo = DingDingUtils.getDepartmentNewList(accessToken, parentId);

        // 使用FastJSON解析JSON字符串
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(deptInfo);
        // 检查errcode是否为0，即请求是否成功
        if (jsonObject.getIntValue("errcode") != 0) {
            throw new RuntimeException("Failed to fetch department list: " + jsonObject.getString("errmsg"));
        }
        // 获取"result"数组
        com.alibaba.fastjson.JSONArray resultArray = jsonObject.getJSONArray("result");

        // 遍历"result"数组
        for (int i = 0; i < resultArray.size(); i++) {
            com.alibaba.fastjson.JSONObject department = resultArray.getJSONObject(i);
            // 提取每个部门的信息
         /*   boolean autoAddUser = department.getBoolean("auto_add_user");
            boolean createDeptGroup = department.getBoolean("create_dept_group");*/
            int deptId = department.getIntValue("dept_id");
            String name = department.getString("name");
            int parent_id = department.getIntValue("parent_id");

            // 判断当前部门是否有子部门
            boolean hasChildren = !DingDingUtils.getDepartmentNewList(accessToken, String.valueOf(deptId)).isEmpty();

            // 根据父ID处理角色信息
            if(parent_id == 1){
                // 创建或更新部门信息
                Role role = new Role();
                role.setName(name);
                role.setSortNumber(i + 1);
                role.setIsProduce(true); // 如果没有子部门，则设置为false，否则为true
                role.setIsDeleted(true);
                role.setDingDepartmentId(Long.valueOf(deptId));
                //TODO 取根部门下面的夫定的编码 topParentId
                role.setDingParentId(Long.valueOf(parent_id));
                role.setParentId(topParentId);
                role.setCode(generateSixDigitNumber(name));
                Role role2 = baseMapper.getRoleDepartData(null, Long.valueOf(deptId));
                if(role2 != null){
                    role.setId(role2.getId());
                    baseMapper.updateById(role);
                } else {
                    baseMapper.insert(role);
                }
            } else {
                Role role3 = baseMapper.getRoleDepartData(null, Long.valueOf(parentId));
                if(role3 != null){
                    // 创建或更新部门信息
                    Role role = new Role();
                    role.setName(name);
                    role.setSortNumber(i + 1);
                    role.setIsProduce(false); // 如果没有子部门，则设置为false，否则为true
                    role.setIsDeleted(true);
                    role.setDingDepartmentId(Long.valueOf(deptId));
                    role.setDingParentId(Long.valueOf(parent_id));
                    role.setParentId(role3.getId());
                    role.setCode(generateSixDigitNumber(name));
                    Role role2 = baseMapper.getRoleDepartData(null, Long.valueOf(deptId));
                    if(role2 != null){
                        role.setId(role2.getId());
                        baseMapper.updateById(role);
                    } else {
                        baseMapper.insert(role);
                    }
                }
            }

            // 如果有子部门，递归调用，处理子部门
            if (hasChildren) {
                syncDingDeptToSysRole(accessToken, String.valueOf(deptId),topParentId);
            }
        }
    }


    public static String generateSixDigitNumber(String name) {
        // 使用名字的哈希码作为种子
        int hashCode = name.hashCode();

        // 为了让结果更加随机，可以混合当前时间戳
        long timestamp = System.currentTimeMillis();
        int combinedHash = BigInteger.valueOf(hashCode).xor(BigInteger.valueOf(timestamp)).intValue();

        // 确保得到的是一个正数
        if (combinedHash < 0) {
            combinedHash = -combinedHash;
        }

        // 生成一个六位数（100000到999999之间）
        int sixDigitNumber = 100000 + (combinedHash % 900000);

        return String.valueOf(sixDigitNumber);
    }



}
